﻿#include "ChatController.h"
#include "MessageController.h"
#include "SimpleAudioEngine.h"
#include "device/CADevice.h"
#include <math.h>

ChatController::ChatController(const char* name){
	this->name=name;
	emojis.pushBack(new CAValue("[呲牙]"));
	emojis.pushBack(new CAValue("[调皮]"));
	emojis.pushBack(new CAValue("[流汗]"));
	emojis.pushBack(new CAValue("[偷笑]"));
	emojis.pushBack(new CAValue("[再见]"));
	emojis.pushBack(new CAValue("[敲打]"));
	emojis.pushBack(new CAValue("[擦汗]"));
	emojis.pushBack(new CAValue("[猪头]"));
	emojis.pushBack(new CAValue("[玫瑰]"));
	emojis.pushBack(new CAValue("[流泪]"));
	emojis.pushBack(new CAValue("[大哭]"));
	emojis.pushBack(new CAValue("[嘘]"));
	emojis.pushBack(new CAValue("[酷]"));
	emojis.pushBack(new CAValue("[抓狂]"));
	emojis.pushBack(new CAValue("[委屈]"));
	emojis.pushBack(new CAValue("[便便]"));
	emojis.pushBack(new CAValue("[炸弹]"));
	emojis.pushBack(new CAValue("[菜刀]"));
	emojis.pushBack(new CAValue("[可爱]"));
	emojis.pushBack(new CAValue("[色]"));
	emojis.pushBack(new CAValue("[害羞]"));
	emojis.pushBack(new CAValue("[得意]"));
	emojis.pushBack(new CAValue("[吐]"));
	emojis.pushBack(new CAValue("[微笑]"));
	emojis.pushBack(new CAValue("[发怒]"));
	emojis.pushBack(new CAValue("[尴尬]"));
	emojis.pushBack(new CAValue("[惊恐]"));
	emojis.pushBack(new CAValue("[冷汗]"));
	emojis.pushBack(new CAValue("[爱心]"));
	emojis.pushBack(new CAValue("[示爱]"));
	emojis.pushBack(new CAValue("[白眼]"));
	emojis.pushBack(new CAValue("[傲慢]"));
	emojis.pushBack(new CAValue("[难过]"));
	emojis.pushBack(new CAValue("[惊讶]"));
	emojis.pushBack(new CAValue("[疑问]"));
	emojis.pushBack(new CAValue("[睡]"));
	emojis.pushBack(new CAValue("[亲亲]"));
	emojis.pushBack(new CAValue("[憨笑]"));
	emojis.pushBack(new CAValue("[爱情]"));
	emojis.pushBack(new CAValue("[衰]"));
	emojis.pushBack(new CAValue("[撇嘴]"));
	emojis.pushBack(new CAValue("[阴险]"));
	emojis.pushBack(new CAValue("[奋斗]"));
	emojis.pushBack(new CAValue("[发呆]"));
	emojis.pushBack(new CAValue("[右哼哼]"));
	emojis.pushBack(new CAValue("[拥抱]"));
	emojis.pushBack(new CAValue("[坏笑]"));
	emojis.pushBack(new CAValue("[飞吻]"));
	emojis.pushBack(new CAValue("[鄙视]"));
	emojis.pushBack(new CAValue("[晕]"));
	emojis.pushBack(new CAValue("[大兵]"));
	emojis.pushBack(new CAValue("[可怜]"));
	emojis.pushBack(new CAValue("[强]"));
	emojis.pushBack(new CAValue("[弱]"));
	emojis.pushBack(new CAValue("[握手]"));
	emojis.pushBack(new CAValue("[胜利]"));
	emojis.pushBack(new CAValue("[抱拳]"));
	emojis.pushBack(new CAValue("[凋谢]"));
	emojis.pushBack(new CAValue("[饭]"));
	emojis.pushBack(new CAValue("[蛋糕]"));
	emojis.pushBack(new CAValue("[西瓜]"));
	emojis.pushBack(new CAValue("[啤酒]"));
	emojis.pushBack(new CAValue("[飘虫]"));
	emojis.pushBack(new CAValue("[勾引]"));
	emojis.pushBack(new CAValue("[OK]"));
	emojis.pushBack(new CAValue("[爱你]"));
	emojis.pushBack(new CAValue("[咖啡]"));
	emojis.pushBack(new CAValue("[钱]"));
	emojis.pushBack(new CAValue("[月亮]"));
	emojis.pushBack(new CAValue("[美女]"));
	emojis.pushBack(new CAValue("[刀]"));
	emojis.pushBack(new CAValue("[发抖]"));
	emojis.pushBack(new CAValue("[差劲]"));
	emojis.pushBack(new CAValue("[拳头]"));
	emojis.pushBack(new CAValue("[心碎]"));
	emojis.pushBack(new CAValue("[太阳]"));
	emojis.pushBack(new CAValue("[礼物]"));
	emojis.pushBack(new CAValue("[足球]"));
	emojis.pushBack(new CAValue("[骷髅]"));
	emojis.pushBack(new CAValue("[挥手]"));
	emojis.pushBack(new CAValue("[闪电]"));
	emojis.pushBack(new CAValue("[饥饿]"));
	emojis.pushBack(new CAValue("[困]"));
	emojis.pushBack(new CAValue("[咒骂]"));
	emojis.pushBack(new CAValue("[折磨]"));
	emojis.pushBack(new CAValue("[抠鼻]"));
	emojis.pushBack(new CAValue("[鼓掌]"));
	emojis.pushBack(new CAValue("[糗大了]"));
	emojis.pushBack(new CAValue("[左哼哼]"));
	emojis.pushBack(new CAValue("[哈欠]"));
	emojis.pushBack(new CAValue("[快哭了]"));
	emojis.pushBack(new CAValue("[吓]"));
	emojis.pushBack(new CAValue("[篮球]"));
	emojis.pushBack(new CAValue("[乒乓球]"));
	emojis.pushBack(new CAValue("[NO]"));
	emojis.pushBack(new CAValue("[跳跳]"));
	emojis.pushBack(new CAValue("[怄火]"));
	emojis.pushBack(new CAValue("[转圈]"));
	emojis.pushBack(new CAValue("[磕头]"));
	emojis.pushBack(new CAValue("[回头]"));
	emojis.pushBack(new CAValue("[跳绳]"));
	emojis.pushBack(new CAValue("[激动]"));
	emojis.pushBack(new CAValue("[街舞]"));
	emojis.pushBack(new CAValue("[献吻]"));
	emojis.pushBack(new CAValue("[左太极]"));
	emojis.pushBack(new CAValue("[右太极]"));
	emojis.pushBack(new CAValue("[闭嘴]"));
}

ChatController::~ChatController(){}

ChatController* ChatController::create(const char* name){
	ChatController* me=new ChatController(name);
	if(me&&me->init()){
		me->autorelease();

		return me;
	}else{
		delete me;
		me=nullptr;

		return nullptr;
	}
}

void ChatController::viewDidLoad(){
	font.fontSize=35;
    CAView* view=this->getView();
	this->setNavigationBarItem(CANavigationBarItem::create(this->name));

	socket=new WebSocket();
	socket->init(*this, "ws://127.0.0.1:8088/website/websocket.ws/1");

	scrollView=CAScrollView::createWithLayout(DLayout(DHorizontalLayoutFill, DVerticalLayout_T_B(0, 130)));
	scrollView->setBounceHorizontal(false);
	scrollView->setHorizontalScrollEnabled(false);
	scrollView->setShowsHorizontalScrollIndicator(false);
	view->addSubview(scrollView);
	curWidth=scrollView->getBounds().size.width;
	maxWidth=curWidth*0.6;
	sendNode=CAView::createWithLayout(DLayout(DHorizontalLayoutFill, DVerticalLayout_B_H(0, 120)), CAColor_gray);
	view->addSubview(sendNode);
	inputField=CATextField::createWithLayout(DLayout(DHorizontalLayout_L_R(10, 120), DVerticalLayout_T_H(10, 100)));
	inputField->setTextTag("normal");
	inputField->setPlaceHolderText("请输入聊天内容");
	inputField->setMarginImageRight(DSize(96, 96), "img/emoji_normal.png");
	inputField->onShouldBeginEditing([=]{
		inputField->setTextTag("normal");
		inputField->setMarginImageRight(DSize(96, 96), "img/emoji_normal.png");
		sendNode->setLayout(DLayout(DHorizontalLayoutFill, DVerticalLayout_B_H(0, 120)));
		view->removeSubviewByTag(107);

		return false;
	});
	sendNode->addSubview(inputField);
	CAButton* countenance=(CAButton*)inputField->getSubviewByTag(2);
	countenance->addTarget([=]{
		if(inputField->getTextTag()=="normal"){
			inputField->setTextTag("activated");
			inputField->setMarginImageRight(DSize(96, 96), "img/emoji_activated.png");
			sendNode->setLayout(DLayout(DHorizontalLayoutFill, DVerticalLayout_B_H(500, 120)));
			CAView* baseView=CAView::createWithLayout(DLayout(DHorizontalLayoutFill, DVerticalLayout_B_H(0, 500)));
			baseView->setTag(107);
			emojiView=CAAutoCollectionView::createWithLayout(DLayout(DHorizontalLayout_L_R(10, 10), DVerticalLayoutFill));
			emojiView->setTag(100);
			emojiView->setBounces(false);
			emojiView->setHoriCellInterval(20);
			emojiView->setVertCellInterval(20);
			emojiView->setAllowsSelection(true);
			emojiView->setShowsScrollIndicators(false);
			emojiView->setOrientation(CAAutoCollectionView::Orientation::Vertical);
			emojiView->onCellAtIndexPath(CALLBACK_BIND_3(ChatController::collectionCellAtIndex, this));
			emojiView->onNumberOfItemsAtIndexPath(CALLBACK_BIND_1(ChatController::numberOfItemsInSection, this));
			emojiView->onCellSizeAtIndexPath(CALLBACK_BIND_2(ChatController::collectionViewCellSizeAtIndexPath, this));
			emojiView->onDidSelectCellAtIndexPath(CALLBACK_BIND_2(ChatController::collectionViewDidSelectCellAtIndexPath, this));
			baseView->addSubview(emojiView);
			view->addSubview(baseView);
		}else{
			inputField->setTextTag("normal");
			inputField->setMarginImageRight(DSize(96, 96), "img/emoji_normal.png");
			sendNode->setLayout(DLayout(DHorizontalLayoutFill, DVerticalLayout_B_H(0, 120)));
			view->removeSubviewByTag(107);
		}
	}, CAButton::Event::TouchDown);
	CAButton* sendBtn=CAButton::createWithLayout(DLayout(DHorizontalLayout_L_R(inputField->getBounds().size.width+20, 10), DVerticalLayout_T_H(10, 100)), CAButton::Type::RoundedRect);
	sendBtn->setTitleForState(CAControl::State::Normal, "发送");
	sendBtn->addTarget([=]{
		std::string msgData=inputField->getText();
		if(msgData.empty()){
			getAlert(view, "请输入聊天内容");
			return;
		}else if(msgData.length()>150){
			getAlert(view, "聊天内容输入输入50个字");
			return;
		}

		socket->send(msgData);
		addNewMsg(msgData, true);
		inputField->setText("");
	}, CAButton::Event::TouchDown);
	sendNode->addSubview(sendBtn);
}

void ChatController::viewDidUnload(){
	socket->close();
}

void ChatController::collectionViewDidSelectCellAtIndexPath(unsigned int section, unsigned int item){
	CACollectionViewCell* cell=emojiView->cellForRowAtIndexPath(section, item);
	socket->send(emojis.at(item)->asString());
	addNewMsg(emojis.at(item)->asString(), true);
	inputField->setText("");
	inputField->setTextTag("normal");
	inputField->setMarginImageRight(DSize(96, 96), "img/emoji_normal.png");
	sendNode->setLayout(DLayout(DHorizontalLayoutFill, DVerticalLayout_B_H(0, 120)));
	this->getView()->removeSubviewByTag(107);
}

CACollectionViewCell* ChatController::collectionCellAtIndex(const DSize& cellSize, unsigned int section, unsigned int item){
	CACollectionViewCell* cell=emojiView->dequeueReusableCellWithIdentifier("emojiCell");
	if(cell==nullptr){
		cell=CACollectionViewCell::create("emojiCell");
		CAImageView* emojiImg=CAImageView::createWithLayout(DLayout(DHorizontalLayoutFill, DVerticalLayout_T_H(0, 56)));
		emojiImg->setTag(99);
		cell->getContentView()->addSubview(emojiImg);
	}
	CAImageView* emojiImg=(CAImageView*)cell->getContentView()->getSubviewByTag(99);
	emojiImg->setImage(CAImage::create(obj2str("emoji/f_static_%03d.png", item)));

	return cell;
}

DSize ChatController::collectionViewCellSizeAtIndexPath(unsigned int section, unsigned int item){
	return DSize(56, 56);
}

unsigned int ChatController::numberOfItemsInSection(unsigned int section){
	return (unsigned int)emojis.size();
}

void ChatController::addNewMsg(std::string msg, bool isMe){
	font.fontSize=35;
	font.lineSpacing=20;
	int size=size4utf8(msg);
	int length=msg.length();
	int sizes=(length-size)/2.0f;
	float width=size*40+(size-sizes)*22.5;
	float height=100.0f;
	float row=width/maxWidth;
	if(width>maxWidth){
		width=maxWidth;
		if(row>1){
			height=row*40+60;
		}
	}else if(width<89){
		width=89.0f;
	}
	CARichLabel* label=nullptr;
	CAGifView* emoji=nullptr;
	float top=curHeight-20;
	if(isMe){
		CAImageView* avatarView=CAImageView::createWithLayout(DLayout(DHorizontalLayout_R_W(20, 85), DVerticalLayout_T_H(top, 85)));
		avatarView->setImage(CAImage::create("img/me.jpg"));
		scrollView->addSubview(avatarView);
		CAImageView* maskView=CAImageView::createWithLayout(DLayout(DHorizontalLayout_R_W(20, 85), DVerticalLayout_T_H(top, 85)));
		maskView->setImage(CAImage::create("img/mask_image.png"));
		scrollView->addSubview(maskView);
		std::string value="";
		if(size<6&&msg.find('[')==0&&msg.find(']')==msg.length()-1){
			for(int i=0, length=emojis.size(); i<length; ++i){
				value=emojis.at(i)->asString();
				if(value==msg){
					emoji=CAGifView::createWithLayout(DLayout(DHorizontalLayout_R_W(156, 56), DVerticalLayout_T_H(curHeight+20, 56)));
					emoji->setGif(CAGif::create(obj2str("emoji/f%03d.gif", i)));
					emoji->setRepeatForever(true);
					emoji->setZOrder(100);
					scrollView->addSubview(emoji);
					width=100;
					height=100;
					break;
				}
			}
		}
		if(value.empty()){
			label=CARichLabel::createWithLayout(DLayout(DHorizontalLayout_R_W(129, width), DVerticalLayout_T_H(curHeight, height)));
			label->setVerticalTextAlignmet(CAVerticalTextAlignment::Center);
			if(size<3){
				label->setTextAlignment(CATextAlignment::Center);
			}else{
				label->setTextAlignment(CATextAlignment::Left);
			}
			label->setZOrder(100);
			label->appendText(msg, font);
			scrollView->addSubview(label);
		}
		CAImageView* corner=CAImageView::createWithLayout(DLayout(DHorizontalLayout_R_W(105, 30), DVerticalLayout_T_H(curHeight+20, 30)));
		corner->setImage(CAImage::create("img/chat_bg_me_corner.png"));
		scrollView->addSubview(corner);
		CAScale9ImageView* bg_me=CAScale9ImageView::createWithImage(CAImage::create("img/chat_bg_me.png"));
		bg_me->setLayout(DLayout(DHorizontalLayout_R_W(130, width), DVerticalLayout_T_H(curHeight, height)));
		scrollView->addSubview(bg_me);
	}else{
		CAImageView* otherView=CAImageView::createWithLayout(DLayout(DHorizontalLayout_L_W(20, 85), DVerticalLayout_T_H(top, 85)));
		otherView->setImage(CAImage::create("img/other.jpg"));
		scrollView->addSubview(otherView);
		CAImageView* maskView=CAImageView::createWithLayout(DLayout(DHorizontalLayout_L_W(20, 85), DVerticalLayout_T_H(top, 85)));
		maskView->setImage(CAImage::create("img/mask_image.png"));
		scrollView->addSubview(maskView);
		std::string value="";
		if(size<6&&msg.find('[')==0&&msg.find(']')==msg.length()-1){
			for(int i=0, length=emojis.size(); i<length; ++i){
				value=emojis.at(i)->asString();
				if(value==msg){
					emoji=CAGifView::createWithLayout(DLayout(DHorizontalLayout_L_W(156, 56), DVerticalLayout_T_H(curHeight+20, 56)));
					emoji->setGif(CAGif::create(obj2str("emoji/f%03d.gif", i)));
					emoji->setRepeatForever(true);
					emoji->setZOrder(100);
					scrollView->addSubview(emoji);
					width=100;
					height=100;
					break;
				}
			}
		}
		if(value.empty()){
			label=CARichLabel::createWithLayout(DLayout(DHorizontalLayout_L_W(129, width), DVerticalLayout_T_H(curHeight, height)));
			label->setVerticalTextAlignmet(CAVerticalTextAlignment::Center);
			if(size<3){
				label->setTextAlignment(CATextAlignment::Center);
			} else{
				label->setTextAlignment(CATextAlignment::Left);
			}
			label->setZOrder(100);
			label->appendText(msg, font);
			scrollView->addSubview(label);
		}
		CAImageView* corner=CAImageView::createWithLayout(DLayout(DHorizontalLayout_L_W(105, 30), DVerticalLayout_T_H(curHeight+20, 30)));
		corner->setImage(CAImage::create("img/chat_bg_other_corner.png"));
		scrollView->addSubview(corner);
		CAScale9ImageView* bg_other=CAScale9ImageView::createWithImage(CAImage::create("img/chat_bg_other.png"));
		bg_other->setLayout(DLayout(DHorizontalLayout_L_W(130, width), DVerticalLayout_T_H(curHeight, height)));
		scrollView->addSubview(bg_other);
	    CocosDenshion::SimpleAudioEngine::sharedEngine()->playBackgroundMusic("html/msg.wav", false);
	}
	if(label==nullptr){
		curHeight+=emoji->getBounds().size.height+50;
	}else{
		curHeight+=label->getBounds().size.height+30;
	}
	scrollView->setViewSize(DSize(scrollView->getBounds().size.width, curHeight+50));
	float offsetHeight=curHeight-scrollView->getBounds().size.height;
	if(offsetHeight>0&&curHeight>offsetHeight){
		scrollView->setContentOffset(DPoint(0, offsetHeight+50), true);
	}
}

void ChatController::onOpen(WebSocket* ws){
	CCLog("=================>WebSocket已打开");
}

void ChatController::onMessage(WebSocket* ws, const WebSocket::Data& data){
	if(data.isBinary){//二进制数据的处理
		std::string result;
		for(int i=0, length=data.len; i<length; i++){
			if(data.bytes[i]=='\0'){
				result+="\'\\0\'";
			}else{
				result+=data.bytes[i];
			}
		}
	}else{//文本数据
		addNewMsg(data.bytes, false);
	}
}

void ChatController::onClose(WebSocket* ws){
	CCLog("=================>WebSocket已关闭");
}

void ChatController::onError(WebSocket* ws, const WebSocket::ErrorCode& error){
	CADevice::sendLocalNotification("1+2生鲜", "服务器连接失败", 100);
}